package com.kitty.web.common;

import com.alibaba.fastjson.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取地址类
 *
 * @author soul
 */
public class AddressUtils
{
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String IP_URL = "https://ip.taobao.com/outGetIpInfo";

    public static void main(String[] args) {
        getRealAddressByIP("101.42.231.47");
    }
    public static String getRealAddressByIP(String ip){
        Map<String,String> map = new HashMap();
        map.put("ip",ip);
        map.put("accessKey","alibaba-inc");

        String rspStr = null;
        try {
            rspStr = HttpUtils.doPost(IP_URL, map);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (StringUtils.isEmpty(rspStr)){
            log.error("获取地理位置异常 {}", ip);
        }
        String region= "";
        try {
            JSONObject obj = JSONObject.parseObject(rspStr);

            JSONObject data = obj.getObject("data", JSONObject.class);
            region = data.getString("region");
        }catch(Exception e){
            log.info("出现错误：{}",e);
        }
        return region;
    }
}
